// @ts-ignore
import {
  exportInterface,
  queryInterfaceByPage,
  saveInterface,
} from '@/services/ant-design-pro/interfaceInfoController';
import { QuestionCircleOutlined, SyncOutlined } from '@ant-design/icons';
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
  TableDropdown,
} from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form/lib';
import { Button, FloatButton, Form, message } from 'antd';
import React, { useRef, useState } from 'react';
import {exportExcel} from "@/common/ExcelUtils";

const Index: React.FC = () => {
  const tableActionRef = useRef<ActionType>();

  /**
   * 接口相关Modal表单
   * ---------------------------
   */
  const [form] = Form.useForm<{ name: string; company: string }>();
  const [modalVisible, setModalVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);

  const modalVisibleChange = (visible: boolean, key: string, record: API.InterfaceInfoEntity) => {
    // modal显示的时候发送请求
    if (visible && key === 'edit') {
      form.setFieldsValue(record);
      setIsEdit(true);
    }
    if (visible && key === 'add') {
      setIsEdit(false);
    }
    setModalVisible(visible);
  };

  const addOrEditInterface = async (values: API.InterfaceInfoEntity) => {
    if (isEdit) {
      const res = await update2(values);
      if (res?.code === 200) {
        message.success('编辑成功');
        tableActionRef.current?.reload();
        setModalVisible(false);
        return;
      }
      message.error(res?.message);
    } else {
      alert(JSON.stringify(values));
      const res = await saveInterface(values);
      if (res?.code === 200) {
        message.success('新建成功');
        tableActionRef.current?.reload();
        setModalVisible(false);
        return;
      }
      message.error(res?.message);
    }
    console.log(values);
  };

  /**
   * 接口信息表格相关
   * --------------------------
   */
  const opsInterface = (key: string, record: API.InterfaceInfoEntity) => {
    if (key === 'edit') {
      modalVisibleChange(true, key, record);
    }
  };

  const columns = [
    {
      title: '名称',
      align: 'center',
      dataIndex: 'name',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: '描述',
      align: 'center',
      dataIndex: 'description',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: 'URL',
      dataIndex: 'url',
      valueType: 'textarea',
      hideInSearch: true,
      align: 'center',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '请求类型',
      dataIndex: 'method',
      valueType: 'textarea',
      align: 'center',
    },
    {
      title: '请求参数',
      align: 'center',
      dataIndex: 'requestParam',
      valueType: 'textarea',
      hideInSearch: true,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '请求体',
      align: 'center',
      dataIndex: 'requestBody',
      valueType: 'textarea',
      hideInSearch: true,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '关闭', status: 'Error' },
        1: { text: '开启', status: 'Success' },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text: string, record: any, _: any, action: any) => [
        // <a
        //   key="editable"
        //   // onClick={() => {
        //   //   action?.startEditable?.(record.id);
        //   // }}
        // >
        //   编辑
        // </a>,
        // <a href={record.url} target="_blank" rel="noopener noreferrer" key="view">
        //   查看
        // </a>,
        <TableDropdown
          key="actionGroup"
          onSelect={(key) => opsInterface(key, record)}
          menus={[
            { key: 'edit', name: '编辑' },
            { key: 'view', name: '查看' },
            { key: 'delete', name: '删除' },
          ]}
        />,
      ],
    },
  ];

  const formInterfaceRef = useRef<ProFormInstance>();
  const [pageRequest, setPageRequest] = useState<PageRequest>({
    current: 1,
    pageSize: 10,
  });

  const queryInterfaceByPager = async (
    // 第一个参数 params 查询表单和 params 参数的结合
    // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
    params: PageRequest,
  ) => {
    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
    // 如果需要转化参数可以在这里进行修改
    setPageRequest({
      current: params?.current,
      pageSize: params?.pageSize,
    });
    const msg = await queryInterfaceByPage({
      // pageIndex: params.current,
      // pageSize: params.pageSize,
      ...params,
      ...formInterfaceRef.current?.getFieldsValue(),
    });
    return {
      data: msg?.data?.records,
      // success 请返回 true，
      // 不然 table 会停止解析数据，即使有数据
      success: msg?.code === 200,
      // 不传会使用 data 的长度，如果是分页一定要传
      total: msg?.data?.total,
    };
  };

  /**
   * 导出接口信息
   */
  const exportInterfaceAll = async () => {
    const res = await exportInterface({
      responseType:"blob"
    })
    let blob = new Blob([res]); //res为从后台返回的数据
    let fileName = "接口信息.xlsx";
    exportExcel(fileName,blob)
  }

  return (
    <>
      <FloatButton.Group shape="circle" style={{ insetInlineEnd: 24 }}>
        <FloatButton icon={<QuestionCircleOutlined />} />
        <FloatButton />
        <FloatButton.BackTop visibilityHeight={0} />
      </FloatButton.Group>
      <FloatButton.Group shape="square" style={{ insetInlineEnd: 94 }}>
        <FloatButton icon={<QuestionCircleOutlined />} />
        <FloatButton />
        <FloatButton icon={<SyncOutlined />} />
        <FloatButton.BackTop visibilityHeight={0} />
      </FloatButton.Group>
      <PageContainer title={false} breadcrumbRender={false}>
        <ProTable<API.InterfaceInfoEntity, any>
          // params 是需要自带的参数
          // 这个参数优先级更高，会覆盖查询表单的参数
          headerTitle="接口管理"
          toolBarRender={() => [
            <Button key="add" type={'primary'} onClick={() => modalVisibleChange(true, 'add', {})}>
              新建
            </Button>,
            <Button key="add" type={'primary'} onClick={exportInterfaceAll}>
              导出
            </Button>
          ]}
          actionRef={tableActionRef}
          formRef={formInterfaceRef}
          // params={pageRequest}
          columns={columns as any}
          pagination={pageRequest}
          rowKey="id"
          search={{
            labelWidth: 100,
            span: 6,
          }}
          request={(params) => queryInterfaceByPager(params)}
        />

        <ModalForm<{
          name: string;
          company: string;
        }>
          title={isEdit ? '编辑表单' : '新建表单'}
          open={modalVisible}
          onOpenChange={(visible) => modalVisibleChange(visible, '', {})}
          form={form}
          autoFocusFirstInput
          modalProps={{
            destroyOnClose: true,
            onCancel: () => console.log('run'),
          }}
          submitTimeout={2000}
          onFinish={async (values) => addOrEditInterface(values)}
        >
          <ProFormText
            width="md"
            name="id"
            label="id"
            tooltip="最长为 24 位"
            placeholder="id"
            hidden={true}
          />
          <ProForm.Group>
            <ProFormText
              width="md"
              name="name"
              label="名称"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
              rules={[{ required: true, message: 'Please input your username!' }]}
            />

            <ProFormText
              width="md"
              name="url"
              label="URL"
              placeholder="请输入名称"
              rules={[{ required: true, message: 'Please input your username!' }]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormSelect
              width="md"
              name="method"
              label="类型"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
              rules={[{ required: true, message: 'Please input your username!' }]}
              request={async () => [
                {
                  value: 'GET',
                  label: 'GET',
                },
                {
                  value: 'POST',
                  label: 'POST',
                },
              ]}
            />

            <ProFormSelect
              width="md"
              name="status"
              label="状态"
              placeholder="请输入名称"
              request={async () => [
                {
                  value: 0,
                  label: '关闭',
                },
                {
                  value: 1,
                  label: '开启',
                },
              ]}
            />
          </ProForm.Group>

          <ProForm.Group>
            <ProFormTextArea
              width={'md'}
              name="requestHeader"
              label="请求头"
              placeholder="请输入名称"
            />
            <ProFormTextArea
              width={'md'}
              name="requestParam"
              label="请求参数"
              placeholder="请输入名称"
            />
          </ProForm.Group>
          <ProFormTextArea width="md" name="description" label="描述" />
        </ModalForm>
      </PageContainer>
    </>
  );
};

export default Index;
